package com.veer.shop.service.impl.admin;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.veer.shop.config.Constants;
import com.veer.shop.mapper.MaterialMapper;
import com.veer.shop.param.MaterialsParam;
import com.veer.shop.pojo.Material;
import com.veer.shop.pojo.ResponseData;
import com.veer.shop.pojo.ValidResult;
import com.veer.shop.service.admin.MaterialsService;
import com.veer.shop.utils.DateTimeUtil;
import com.veer.shop.utils.EcryptUtil;
import com.veer.shop.utils.FileUtil;
import com.veer.shop.utils.InitUtil;
import com.veer.shop.utils.ResponseUtil;
import com.veer.shop.utils.SystemConfigUtil;

/**
 * 系统素材管理业务类
 * 
 * @author WangBin
 * 2020年10月6日-下午12:48:47
 */
@Service
public class MaterialsServiceImpl implements MaterialsService{
	
	private Logger logger = LoggerFactory.getLogger(MaterialsServiceImpl.class);
	
	@Autowired
	MaterialMapper materialMapper;
	
	/**
	 * 删除素材
	 */
	@Override
	public ResponseData<?> delete(String materialId, Integer fileDeleted) {
		// TODO Auto-generated method stub
		String[] materialIds = materialId.split(",");
		
		for(String id : materialIds)
		{
			materialMapper.delete(Integer.parseInt(id));
		}
		
		return ResponseUtil.success();
	}
	
	/**
	 * 素材详情
	 */
	@Override
	public ResponseData<?> get(Integer materialId) {
		// TODO Auto-generated method stub
		Material material = materialMapper.getById(materialId);
		
		if(material.getMaterialId() == null)return ResponseUtil.error("素材不存在！");
		
		return ResponseUtil.success(material);
	}
	
	/**
	 * 素材列表
	 */
	@Override
	public ResponseData<?> getList(MaterialsParam materialsListParam, int pageNo, int pageSize) {
		PageMethod.startPage(pageNo, pageSize);
		List<Material> materials = materialMapper.getList(materialsListParam);
		PageInfo pageInfo = new PageInfo(materials);
		return ResponseUtil.success(ResponseUtil.getResponseList(pageInfo.getTotal(), materials));
	}
	
	/**
	 * 新增|更新素材
	 */
	@Override
	public ResponseData<?> update(Material material) {
		// 校验参数
		ValidResult validResult = validMaterial(material);
		
		if(validResult.getCode() == -1) {
			return ResponseUtil.error(validResult.getMessage());
		}
		
		// 相对文件目录
		String relFilePath = "/other";
		
		if(StringUtils.isEmpty(material.getMaterialId())) {
			// 新增
			// 获取base64的文件格式
			String fileType = FileUtil.getBase64FileFormat(material.getBase64Data());
			this.logger.debug("文件格式：" + fileType);
			// 文件格式
			if(StringUtils.isEmpty(fileType)) {
				return ResponseUtil.error("未知的文件格式！");
			}
			
			// 允许的文件格式
			if(!Constants.ALLOEWED_UPLOAD_IMAGE_FORMAT.contains(fileType) && !Constants.ALLOEWED_UPLOAD_VIDEO_FORMAT.contains(fileType)) {
				return ResponseUtil.error("不支持的文件格式！");
			}
			
			// 文件的大小
			double fileSize = FileUtil.getBase64FileSize(material.getBase64Data());
			
			if(Constants.ALLOEWED_UPLOAD_IMAGE_FORMAT.contains(fileType)) {
				if(fileSize > Constants.ALLOEWED_UPLOAD_IMAGE_SIZE) {
					return ResponseUtil.error("图片文件大小不可超过" + Constants.ALLOEWED_UPLOAD_IMAGE_SIZE + "KB！");
				}
				
				relFilePath = SystemConfigUtil.getConfigValue(Constants.SYSTEM_CONFIG_IMAGE_PATH);
			}
			
			if(Constants.ALLOEWED_UPLOAD_VIDEO_FORMAT.contains(fileType)) {
				if(fileSize > Constants.ALLOEWED_UPLOAD_VIDEO_SIZE) {
					return ResponseUtil.error("视频文件大小不可超过" + Constants.ALLOEWED_UPLOAD_VIDEO_SIZE + "KB！");
				}
				
				relFilePath = SystemConfigUtil.getConfigValue(Constants.SYSTEM_CONFIG_VIDEO_PATH);
			}
			
			// 上传文件
			// 存储文件名 年月日 + 随机UUID + 文件格式
			String fileName = DateTimeUtil.getDate().concat(EcryptUtil.generateUUID()).concat(".").concat(fileType);
			String rootPath = SystemConfigUtil.getConfigValue(Constants.SYSTEM_CONFIG_FILE_PATH_ROOT);
			String savePath = rootPath.concat(relFilePath).concat("/");
			boolean result = FileUtil.base64ToFile(fileName, material.getBase64Data(), savePath);
			if(!result)return ResponseUtil.error("上传文件失败！");
			
			// 根据文件类型处理系统需要的数据，如：图片需要获取大中小尺寸、视频需要取第一帧作为封面
			if(Constants.ALLOEWED_UPLOAD_IMAGE_FORMAT.contains(fileType)) {
				Map<String, String> moreSizeMap = FileUtil.getImageMoreSize(savePath.concat(fileName), savePath);
				
				// 文件类型
				material.setType(Constants.FILE_TYPE_IMAGE);
				
				// 图片中图
				material.setMiddleImage(moreSizeMap.get("middle_size"));
				
				// 图片小图
				material.setSmallImage(moreSizeMap.get("small_size"));
				
				// 图片原图
				material.setOriginalImage("/".concat(fileName));
			}
			
			// 视频需要取第一帧作为封面
			if(Constants.ALLOEWED_UPLOAD_VIDEO_FORMAT.contains(fileType)) {
				// TODO 获取视频第一帧作为封面
				
				// 文件类型
				material.setType(Constants.FILE_TYPE_VIDEO);
			}
			
			material.setFileSize(fileSize);
			material.setExtension(fileType);
			material.setCreatedAt(DateTimeUtil.getDateTime());
			material.setUpdatedAt(material.getCreatedAt());
			
			int count = materialMapper.insert(material);
			
			if(count == 0) {
				ResponseUtil.error("文件上传失败！");
			}
		} else {
			// 修改
			
		}
		
		return ResponseUtil.success();
	}
	
	/**
	 * 校验参数
	 * @param material
	 * @return
	 */
	public ValidResult validMaterial(Material material) {
		ValidResult result = InitUtil.initFaildMap();
		
		if(StringUtils.isEmpty(material.getOriginalName())) {
			result.setMessage("上传的文件名不可为空！");
			return result;
		}
		
		if(StringUtils.isEmpty(material.getBase64Data())) {
			result.setMessage("上传的文件不可为空！");
			return result;
		}
		
		return InitUtil.initSuccMap();
	}
}
